"""和书籍有关的数据模型
环境：
    python: v3.12.11
"""

from typing import List, Optional
from pydantic import BaseModel, Field, HttpUrl, field_validator
from datetime import date

from utils.date_parser import parse_date


class Book(BaseModel):
    """用于指代某网站（如当当）上的一本书"""

    name: str = Field(description="书名")
    site_name: str = Field(description="网站名")
    cover_image_url: Optional[HttpUrl] = Field(
        description="图书的封面缩略图URL", default=None
    )
    detail_url: HttpUrl = Field(description="图书详情页URL")
    author: str = Field(description="图书的作者、编者等信息", default="")
    publisher: str = Field(description="图书的出版商", default="")
    isbn: Optional[str] = Field(description="ISBN编码", default=None)
    published_time: Optional[date] = Field(description="出版时间", default=None)

    @field_validator("published_time", mode="before")
    def validate_my_date(cls, v):
        # 如果已经是 date 对象，直接返回
        if isinstance(v, date):
            return v
        # 如果是字符串，用自定义函数解析
        if isinstance(v, str):
            _date = parse_date(v)
            return _date


class BookList(BaseModel):
    """书单"""

    list_name: str = Field(description="清单名，一般用来存储类别，如：少儿文学")
    books: List[Book] = Field(description="书单")


class BookRankList(BaseModel):
    """排名"""

    rank_date: str = Field(description="排名的日期")
    book_ranks: List[BookList] = Field(description="排名是一个BookList类型的容器")
